import React, { useState } from 'react';
import { Button, Form } from 'antd';
import BaseForm from '@/components/baseform';
import CustomInput from './Custom';
import DynamicForm from './Dynamic';
import DynamicFormOld from './DynamicOld';
import moment, { Moment } from 'moment';
import PromiseCustom from './HandlePromise';
import styles from './index.less';

export default (props) => {
  const [num, setNum] = useState(0);
  const [total, setTotal] = useState(0);
  const [listN, setListN] = useState([1, 2]);
  const [form] = Form.useForm();
  const [form2] = Form.useForm();

  const list = [1, 2, 3, 4, 5, 6, 7, 8, 9, null, undefined, 10];

  const asyncFun = () => {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        reject('error'); // catch会处理
      }, 1000);
    });
  };

  const handleTotal = () => {
    let newTotal = 0;
    for (let i = 0; i < list.length; i++) {
      if (!list[i]) {
        continue;
      } //continue会跳出此次循环，继续下个循环
      newTotal += list[i];
    }
    setNum(newTotal);
  };

  const handleAsync = async () => {
    try {
      const result = await asyncFun();
      console.log(result);
    } catch (e) {
      console.log(e, '--err');
    } finally {
      console.log('-finally-');
    }
  };

  const handleForeach = () => {
    const obj = ['001', '002', '003'];
    try {
      obj.forEach((item) => {
        console.log(`当前id：${item}`);
        if (item === '002') {
          throw new Error('id等于002，跳出循环');
        }
      });
    } catch (error) {
      console.error(error);
    }
    console.log('如果看见了这段话说明代码没有被报错所阻塞');
  };

  const reduceFun = () => {
    const list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    let list_new = list.reduce((count, currItem) => {
      // count：每次函数的累积的返回值
      // currItem:数组当前循环到的值
      return count + currItem;
    }, 0);
    setTotal(list_new);
  };

  const [searchParam, setSearchParam] = useState();
  const handleSearch = (obj) => {
    console.log(obj, '--obj');
  };

  const changeCustom = (value) => {
    console.log();
  };

  const search = () => {
    // form.validateFields().then((data) => {
    //     console.log(data, '--values-form1')
    //     Object.keys(data).forEach(i => {
    //         if (i.indexOf('$btw') !== -1 || i.indexOf('$BTW') !== -1) {
    //             if (data[i]) {
    //             const formatDate = data[i].map((e) => moment(e).format('YYYY-MM-DD HH:mm:ss'));
    //             data[i] = formatDate.join(',');
    //             }
    //         }
    //         });

    //     console.log(data, '--data')
    // })
    Promise.all([form.validateFields(), form2.validateFields()]).then(
      (result) => {
        console.log(result, '--result');
      },
    );
    // const data = form.getFieldsValue();
  };

  const testCustomPromise = () => {
    let promise = new PromiseCustom((resolve, reject) => {
      setTimeout(() => {
        resolve('resolve--test');
      }, 3000);
    });
    promise.then((val) => {
      console.log('111', val);
    });
  };

  return (
    <div>
      <div className={styles.wrap}>
        <div className={styles.inner_wrap}>
          <Button type="primary" onClick={handleTotal}>
            continue测试
          </Button>
          :{num}{' '}
        </div>
        <div className={styles.inner_wrap}>
          <Button type="primary" onClick={handleAsync}>
            try-catch-async/await
          </Button>{' '}
        </div>
        <div className={styles.inner_wrap}>
          <Button type="primary" onClick={testCustomPromise}>
            手写Promise
          </Button>{' '}
        </div>
        <div className={styles.inner_wrap}>
          <Button type="primary" onClick={handleForeach}>
            try-catch-foreach
          </Button>
          <div className={styles.inner_wrap_info}>
            foreach:没有break,可以通过try/catch抛出错误终止循环
          </div>
        </div>
        <div>
          {listN.map((item) => (
            <>{item}</>
          ))}
          {/* {listN.map(function(item){
                return <>{item}</>
              })} */}
        </div>
        <div className={styles.inner_wrap}>
          <Button type="primary" onClick={reduceFun}>
            reduce
          </Button>
          :{total}
          <div className={styles.inner_wrap_info}>
            reduce: 两个参数
            <br />
            参数一：函数(两个参数，第一次循环是初始值和数组第一个，第二次是函数返回值和数组第二个.....)
            参数二：初始值
          </div>
        </div>
      </div>
      <BaseForm
        search={search}
        form={form}
        formItems={[
          {
            label: '产品ID',
            key: 'productId$LIKE',
            type: 'string',
            ruleList: [{ required: true, message: '必须填产品' }],
          },
          {
            label: '设备ID',
            key: 'deviceId$LIKE',
            type: 'string',
            ruleList: [{ required: true, message: '必须填设备' }],
          },
          {
            label: '下发时间',
            key: 'sendTimestamp$btw',
            type: 'time',
          },
          {
            label: '自定义组件',
            key: 'customComponent',
            type: 'custom',
            components: <CustomInput defaultValue={'customValue'} />,
          },
        ]}
      />
      {/* <DynamicForm form={form2} defaultList={[]} /> */}
      <DynamicFormOld form={form2} defaultList={[1, 2]} />
      <div
        style={{
          float: 'right',
          marginBottom: 24,
          marginRight: 30,
          marginTop: 4,
        }}
      >
        <Button
          type="primary"
          onClick={() => {
            search();
          }}
        >
          查询
        </Button>
        <Button
          style={{ marginLeft: 8 }}
          onClick={() => {
            form.resetFields();
            form2.resetFields();
            //   props.search();
          }}
        >
          重置
        </Button>
        {/* {formItems.length > 2 && (
            <a style={{ marginLeft: 8 }} onClick={() => setExpand(!expand)}>
              {expand ? '展开' : '收起'} <Icon type={expand ? 'down' : 'up'} />
            </a>
          )} */}
      </div>
    </div>
  );
};
